package com.enqualcomm.kids.view;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewPropertyAnimator;

/**
 * Created by yinzhiqun on 2016/1/21.
 */
public class FreshView extends View {

    private static final int DURATION = 300;//松开时执行缩放动画的时长
    private static final float MIN_SCALE = 0.75f;//按下时，最小缩放比例

    private ViewPropertyAnimator touchDownAnimator;
    private boolean canceled;

    public FreshView(Context context) {
        this(context, null);
    }

    public FreshView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public FreshView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        setClickable(true);
    }


    @Override
    public boolean onTouchEvent(MotionEvent event) {
        //要求按下时，开始缩小
        switch (event.getAction()){
            case MotionEvent.ACTION_DOWN:
                startZoomInAnimation();
                break;
            case MotionEvent.ACTION_MOVE:
                if (canceled){
                    break;
                }
                float x = event.getX();
                float y = event.getY();

                if (x>getMeasuredWidth() ||x<0 ||y>getMeasuredHeight()|| y<0){
                    canceled = true;//不再处理后续事件
                    startZoomOutAnimation();
                }
                break;
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_CANCEL:
                if (canceled){
                    canceled = false;
                    break;
                }
                startZoomOutAnimation();
                break;
        }
        return super.onTouchEvent(event);
    }

    private void startZoomInAnimation() {//缩小
        if (touchDownAnimator !=null){
            touchDownAnimator.cancel();
        }

        touchDownAnimator = animate().scaleX(MIN_SCALE)
                .scaleY(MIN_SCALE)
                .setDuration((long) ((getScaleX() - MIN_SCALE) / (1.0f - MIN_SCALE) * DURATION));
        touchDownAnimator.start();
    }

    private void startZoomOutAnimation() {//还原成原始大小
        if (touchDownAnimator !=null){
            touchDownAnimator.cancel();
        }

        touchDownAnimator = animate().scaleX(1.0f)
                .scaleY(1.0f)
                .setDuration((long) ((1.0f-getScaleX())/(1.0f-MIN_SCALE)*DURATION));
        touchDownAnimator.start();
    }
}
